package com.test.controller;

import com.test.dao.MyShowRepository;
import com.test.dt0.MyShowResult;
import com.test.entity.MyShow;
import com.test.service.MyShowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * api 接口
 * Created by apple on 2017/5/12.
 */
@RestController()
@RequestMapping("/myshow")
public class MyShowController {
    @Autowired
    private MyShowRepository myShowRepository;
    @Autowired
    private MyShowService myShowService;

    @GetMapping(value = "/list")
    public List<MyShow> list() {
        return myShowRepository.findAll();
    }

    @PostMapping(value = "/add")
    public MyShow add(@RequestParam("name") String username) {
        MyShow myShow = new MyShow();
        myShow.setName(username);
        return myShowRepository.save(myShow);
    }

    @GetMapping(value = "/get/{id}")
    public MyShow get(@PathVariable("id") Integer id) {
        return myShowRepository.findOne(id);
    }

    @PostMapping(value = "/modify/{id}")
    public MyShow modify(@PathVariable("id") Integer id, @RequestParam("name") String username) {
        MyShow myShow = myShowRepository.findOne(id);
        if (myShow == null) {
            return null;
        }
        myShow.setName(username);
        return myShowRepository.save(myShow);
    }

    @DeleteMapping(value = "/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id) {
        MyShow myShow = myShowRepository.findOne(id);
        if (myShow == null) {
            return false;
        }
        myShowRepository.delete(id);
        return true;
    }

    @GetMapping(value = "/list/{name}")
    public List<MyShow> listByName(@PathVariable("name") String name) {
        return myShowRepository.findByName(name);
    }

    @PostMapping(value = "/add/two")
    public void addTwo() {
        myShowService.inertTow();
    }


    @PostMapping(value = "/add2")
    public MyShowResult<MyShow> add2(@Valid MyShow myShow, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
                return new MyShowResult<>(1, bindingResult.getFieldError().getDefaultMessage());
        }
        return new MyShowResult<>(myShowRepository.save(myShow));
    }

    @GetMapping(value = "/execute/{id}")
    public MyShowResult execute(@PathVariable("id") Integer id) throws Exception{
        return new MyShowResult<>(myShowService.execute(id));
    }
}
